<template>
  <div class="dialog-container">
    <div class="dialog-content">
      <div class="panel-container">
        <div class="panel-content">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="120px"
            style="padding-right: 40px"
          >
            <el-form-item
              prop="head_img"
              label="头像:"
            >
              <ImageUpload
                ref="ImageUpload"
                info-type="avatar"
                @change="onAvatarChange"
              />
            </el-form-item>
            <el-form-item
              prop="name"
              label="用户姓名:"
            >
              <el-input
                v-model="form.name"
                placeholder="请输入用户姓名"
                maxlength="20"
              />
            </el-form-item>
            <el-form-item
              prop="phone"
              label="手机号:"
            >
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item
              prop="account"
              label="账号:"
            >
              <el-input
                v-model="form.account"
                placeholder="请输入账号"
                maxlength="20"
              />
            </el-form-item>
            <el-form-item
              v-if="editModel === 'add'"
              prop="password"
              label="密码:"
            >
              <el-input
                v-model="form.password"
                show-password
                autocomplete="new-password"
                placeholder="请输入密码"
                maxlength="20"
              />
            </el-form-item>
            <el-form-item
              v-if="editModel === 'add'"
              prop="password1"
              label="确认密码:"
            >
              <el-input
                v-model="form.password1"
                show-password
                placeholder="请再次输入密码"
                maxlength="20"
              />
            </el-form-item>
            <el-divider />
            <el-form-item
              label="部门:"
              prop="dept_id"
            >
              <el-cascader
                v-model="form.dept_id"
                :options="optionsDept"
                :props="propsDept"
                collapse-tags
                clearable
              />
            </el-form-item>
            <el-form-item
              label="业务模块:"
              prop="part"
            >
              <el-select
                v-model="form.part"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in BusinessModuleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="等级:"
              prop="part"
            >
              <el-select
                v-model="form.level"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in UserLevelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="数据权限:"
              prop="data_dept_ids"
            >
              <el-cascader
                v-model="form.data_dept_ids"
                :options="optionsData"
                :props="propsData"
                collapse-tags
                clearable
              />
            </el-form-item>
            <el-form-item
              label="角色:"
              prop="rolesIds"
            >
              <el-select
                v-model="form.rolesIds"
                multiple
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="editModel === 'edit'"
              label="在职状态:"
              prop="rz_sts"
            >
              <el-select
                v-model="form.rz_sts"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in JobStatusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="入职日期:"
              prop="rz_date"
            >
              <el-date-picker
                v-model="form.rz_date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-button @click="handleCancel">取消</el-button>
              <el-button
                :loading="loading"
                type="primary"
                @click="handleSubmit"
              >
                提交
              </el-button>
              <el-button
                v-if="editModel === 'edit'"
                :loading="loading"
                type="danger"
                @click="handleDelete"
              >
                删除
              </el-button>
              <el-button
                v-if="editModel === 'edit'"
                :loading="loading"
                type="warning"
                @click="handleResetPassword"
              >
                重置密码
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiUserAdd, apiUserEdit, apiUserDel } from '@/api/system'
import { isPassword, isMobile } from '@/utils/validate'
import {
  BusinessModuleList,
  UserLevelList,
  JobStatusList
} from '@/utils/constant'
import ImageUpload from '@/components/audio/ImageUpload.vue'

export default {
  name: 'DialogAdd',
  components: { ImageUpload },
  props: {
    editModel: {
      type: String,
      default: 'add'
    },
    info: {
      type: Object,
      default: () => {
        return {}
      }
    },
    roleList: {
      type: Array,
      default: () => {
        return []
      }
    },
    deptList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    var validaMobile = (rule, value, callback) => {
      if (value && !isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    var validaPassword = (rule, value, callback) => {
      if (value && !isPassword(value)) {
        callback(new Error('密码6~20位 必须含大写字母、小写字母、数字'))
      } else {
        callback()
      }
    }
    var validaPassword1 = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      BusinessModuleList,
      UserLevelList,
      JobStatusList,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      loading: false,
      form: {
        head_img: '',
        name: '',
        phone: '',
        account: '',
        password: '',
        password1: '',
        dept_id: [],
        part: '',
        level: '',
        rolesIds: [],
        data_dept_ids: [],
        rz_sts: '',
        rz_date: ''
      },
      rules: {
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validaPassword, trigger: 'blur' }
        ],
        password1: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validaPassword1, trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validaMobile, trigger: 'blur' }
        ],
        data_dept_ids: [
          { required: true, message: '请选择数据权限', trigger: 'blur' }
        ]
      },
      propsDept: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      optionsDept: [],
      propsData: {
        value: 'id',
        label: 'name',
        children: 'children',
        multiple: true
      },
      optionsData: []
    }
  },
  mounted() {
    if (this.editModel === 'edit' && this.info) {
      for (const key in this.form) {
        if (key !== 'password' && key !== 'password1') {
          this.form[key] = this.info[key]
        }
      }
    }
    if (this.form.head_img) {
      this.$refs.ImageUpload.setValue(this.form.head_img)
    }
    this.optionsDept = this.optionsData = this.deptList
    console.log(this.info, this.form)
  },
  destroyed() {},
  methods: {
    // 取消
    handleCancel() {
      this.$emit('close')
    },
    // 提交
    handleSubmit() {
      const submitForm = { ...this.form }
      submitForm.dept_id = submitForm.dept_id[submitForm.dept_id.length - 1]
      console.log('apiUserAdd', submitForm)
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        this.loading = true
        if (this.editModel === 'add') {
          apiUserAdd(submitForm)
            .then((res) => {
              this.loading = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              setTimeout(() => {
                this.$emit('success')
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        } else if (this.editModel === 'edit') {
          apiUserEdit({ id: this.info.id, ...this.form })
            .then((res) => {
              this.loading = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              setTimeout(() => {
                this.$emit('success')
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    // 删除
    handleDelete() {
      window.enterPreventDefault = false
      this.$confirm('确定要删除这个账号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          window.enterPreventDefault = true
          this.loading = true
          apiUserDel({ ids: [this.info.id] })
            .then((res) => {
              this.loading = false
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.$emit('success')
            })
            .catch(() => {
              this.loading = false
            })
        })
        .catch(() => {
          window.enterPreventDefault = true
        })
    },
    // 重置密码
    handleResetPassword() {
      this.$emit('resetPassword')
    },
    // 头像上传
    onAvatarChange(val) {
      this.form.head_img = val
    }
  }
}
</script>
